﻿using System.Configuration;
using System.Drawing;
using System.Web;
using WFramework.Utility;
using System.IO;
namespace WFramework
{
    public class ValidateCodeService
    {
        private static readonly string ValidCodeSessionName = ConfigurationManager.AppSettings["ValidCodeName"] ??
                                                           "ValidCodeSessionName";
        
        public Image CreateCode()
        {
            var validateCode = new ValidateCode();
            string code;
            var image = validateCode.CreateImage(80, 20, out code);
            HttpContext.Current.Session[ValidCodeSessionName] = code;
            return image;
        }

        public byte[] CreateCode2(int width,int height)
        {
            ValidateCodeHelper validateCode = new ValidateCodeHelper();
            validateCode.Width = width;
            validateCode.Height = height;
            //生成验证码指定的长度
            string code = validateCode.GetRandomString(4);
            //创建验证码的图片
            byte[] bytes = validateCode.CreateImage(code);
            return bytes;
            //最后将验证码返回
            //return  File(bytes, @"image/jpeg");
            //MemoryStream ms = new MemoryStream(bytes);
            //Image img = Image.FromStream(ms, true);
            //ms.Close();
            //return img;
        }
        public bool CheckCode(string validateCode)
        {
            var isOK = !string.IsNullOrEmpty(validateCode)
                   && HttpContext.Current.Session[ValidCodeSessionName] != null
                   && HttpContext.Current.Session[ValidCodeSessionName].ToString().ToLower() == validateCode.ToLower();
            return isOK;
        }

        public void ClearSession()
        {
            if (HttpContext.Current.Session[ValidCodeSessionName] != null)
                HttpContext.Current.Session.Remove(ValidCodeSessionName);
        }
    }
}